import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:xindong/extension/extension_string.dart';

class XinDongAppDeviceInfo {
  PackageInfo? packageInfo;
  bool isPhysicalDevice = true;
  late String deviceOAID = ""; // 安卓的一种ID
  late String deviceUDID = ""; // 设备唯一标识
  late String deviceName = ""; // 设备名

  // 显示应用名
  String get showAppName {
    return packageInfo?.appName ?? "";
  }

  // 显示版本
  String get showAppVersion {
    return "Version：${packageInfo?.version} (${packageInfo?.buildNumber})";
  }

  // 获取应用和设备信息
  Future<void> getAppInfo() async {
    try {
      final PackageInfo packageInfo = await PackageInfo.fromPlatform();
      XinDongAppDeviceInfo.instance.packageInfo = packageInfo;
    } catch (e) {
      mCatchPrint(e);
    }
    return Future.value();
  }

  // 获取设备信息(需要同意协议才能获取)
  Future<void> getDeviceInfo() async {
    try {
      deviceUDID = await FlutterUdid.udid;
      DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
      if (Platform.isAndroid) {
        AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
        print("object ${androidInfo.toString()}");
        isPhysicalDevice = androidInfo.isPhysicalDevice;
        deviceName = androidInfo.product;
      } else if (Platform.isIOS) {
        IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
        isPhysicalDevice = iosInfo.isPhysicalDevice;
        deviceName = iosInfo.model;
      }
      // 带中文的转义一下，接口不兼容
      if (deviceName.haveChinese) {
        deviceName = Uri.encodeComponent(deviceName);
      }
    } catch (e) {
      mCatchPrint(e);
    }
    return Future.value();
  }

  // 单例
  // 静态变量_instance，存储唯一对象
  static XinDongAppDeviceInfo? _instance;

  // 工厂方法构造函数
  factory XinDongAppDeviceInfo() => _getInstance();

  // instance的getter方法，.instance获取对象
  static XinDongAppDeviceInfo get instance => _getInstance();

  // 获取对象
  static XinDongAppDeviceInfo _getInstance() {
    _instance ??= XinDongAppDeviceInfo._internal();
    return _instance!;
  }

  // 不是关键字，可定义其他名字
  XinDongAppDeviceInfo._internal() {
    //初始化(设置一些默认的)...
  }
}
